// 页面跳转进度条
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "../store";
import { createRouter, createWebHashHistory } from "vue-router";
import authRouter from "./modules/auth";
import shopProductRouter from "./modules/shop_product";
import shopUserRouter from "./modules/shop_user";
import shopPictureRouter from "./modules/shop_picture";
import shopOrderRouter from "./modules/shop_order";
import shopConsultRouter from "./modules/shop_consult";
const routerHistory = createWebHashHistory();

const Login = () =>
  import(
    /* webpackChunkName: 'auth_index' */ "../views/auth/login/login/login.vue"
  );
const Index = () =>
  import(
    /* webpackChunkName: 'auth_index' */ "../views/auth/index/index/index.vue"
  );
const Main = () =>
  import(
    /* webpackChunkName: 'auth_index' */ "../views/auth/index/main/main.vue"
  );
const routes = [
  {
    path: "/",
    component: Index,
    redirect: "/main",
    children: [
      { path: "/main", component: Main },
      ...authRouter,
      ...shopProductRouter,
      ...shopUserRouter,
      ...shopPictureRouter,
      ...shopOrderRouter,
      ...shopConsultRouter
    ]
  },
  { path: "/login", component: Login }
];
const router = createRouter({
  history: routerHistory,
  routes
});
NProgress.inc(1);
NProgress.configure({ easing: "ease", speed: 1000, showSpinner: false });
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // const token = Cookies.get('token')
  const token = localStorage.getItem("token");
  // to 将要访问的路径
  // from 表示从那个路径跳转而来
  // next   next() 表示放行    next('/login')  表示强制跳转
  if (to.path === "/login") {
    if (token) {
      return next("/");
    }
    return next();
  }
  if (!token) {
    return next("/login");
  }
  const visitedViews = store.state.menus.visitedViews;
  var index1 = 0;
  var index2 = 0;
  for (let i = 0; i < visitedViews.length; i++) {
    if ("/" + visitedViews[i].href === to.path) {
      index1 = i;
    }
    if ("/" + visitedViews[i].href === from.path) {
      index2 = i;
    }
  }
  if (index1 < index2) {
    store.commit("config/setTransitionName", "slide-left");
  } else {
    store.commit("config/setTransitionName", "slide-right");
  }

  NProgress.start();
  next();
});
router.afterEach(() => {
  NProgress.done();
});
export default router;
